package com.imay.live.helper;

import android.Manifest;
import android.app.Activity;
import android.hardware.Camera;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.imay.base.helper.ActivityHelper;
import com.imay.capturefilter.utils.PermissionUtil;
import com.imay.dialog.Dialoger;
import com.imay.live.R;
import com.imay.live.activity.BasePermissionActivity;
import com.imay.live.activity.camera.CameraActivity2;
import com.imay.live.activity.camera.ClipActivity;
import com.imay.live.activity.video.RecordVideoActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chan on 2017/6/22 0022.
 */

public class MediaHelper {

    /**
     * 打开拍照
     *
     * @param activity
     * @param req
     */
    public static void startPhoto(@NonNull final Activity activity, final int req) {
        AndPermission.with(activity)
                .requestCode(REQUEST_CODE_PERMISSION_MULTI)
                .permission(new String[]{Manifest.permission.CAMERA})
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        switch (requestCode) {
                            case REQUEST_CODE_PERMISSION_MULTI: {
                                if (grantPermissions.contains(Manifest.permission.CAMERA)) {
                                    if (isFlyme() || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                                        if (checkCamera()) {
                                            CameraActivity2.startActivity(activity, req);
                                        } else {
                                            DialogFragmentHelper.showTipsDialog(((AppCompatActivity) activity).getSupportFragmentManager(), activity.getString(R.string.str_permission_camera), new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    return;
                                                }
                                            });
                                        }
                                    } else {
                                        CameraActivity2.startActivity(activity, req);
                                    }
                                }
                                break;
                            }
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        switch (requestCode) {
                            case REQUEST_CODE_PERMISSION_MULTI: {
                                if (com.imay.live.utils.PermissionUtil.selfPermissionGranted(activity, Manifest.permission.CAMERA)) {
                                    CameraActivity2.startActivity(activity, requestCode);
                                }
                                break;
                            }
                        }
                        if (AndPermission.hasAlwaysDeniedPermission(activity, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(activity, REQUEST_CODE_PERMISSION_MULTI)
                                    .setTitle(R.string.permission_permission_title)
                                    .setMessage(R.string.permission_permission)
                                    .setPositiveButton(R.string.permission_button_setting)
                                    .show();
                        }
                    }
                }).rationale(new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                AndPermission.rationaleDialog(activity, rationale).show();
            }
        }).start();
    }

    private static boolean checkCamera() {
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (mCamera != null) {
                mCamera.release();
            }
        }
        return false;
    }

    private static final int REQUEST_CODE_PERMISSION_MULTI = 101;

    private static boolean isFlyme() {
        if (Build.BRAND.contains("Meizu")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 打开录像
     *
     * @param activity
     */
    public static void startRecord(@NonNull final Activity activity) {
        AndPermission.with(activity)
                .requestCode(REQUEST_CODE_PERMISSION_MULTI)
                .permission(new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA})
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        switch (requestCode) {
                            case REQUEST_CODE_PERMISSION_MULTI: {
                                if (grantPermissions.contains(Manifest.permission.CAMERA)
                                        && grantPermissions.contains(Manifest.permission.RECORD_AUDIO)) {
                                    if (isFlyme() || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                                        if (checkCamera() && checkRecorderPermission()) {
                                            RecordVideoActivity.startActivity(activity);
                                        } else {
                                            DialogFragmentHelper.showTipsDialog(((AppCompatActivity) activity).getSupportFragmentManager(), activity.getString(R.string.str_permission_camera), new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    return;
                                                }
                                            });
                                        }
                                    } else {
                                        RecordVideoActivity.startActivity(activity);
                                    }
                                }
                                break;
                            }
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        switch (requestCode) {
                            case REQUEST_CODE_PERMISSION_MULTI: {
                                if (com.imay.live.utils.PermissionUtil.selfPermissionGranted(activity, Manifest.permission.CAMERA)
                                        && com.imay.live.utils.PermissionUtil.selfPermissionGranted(activity, Manifest.permission.RECORD_AUDIO)) {
                                    RecordVideoActivity.startActivity(activity);
                                }
                                break;
                            }
                        }
                        if (AndPermission.hasAlwaysDeniedPermission(activity, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(activity, REQUEST_CODE_PERMISSION_MULTI)
                                    .setTitle(R.string.permission_permission_title)
                                    .setMessage(R.string.permission_permission)
                                    .setPositiveButton(R.string.permission_button_setting)
                                    .show();
                        }
                    }
                }).rationale(new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                AndPermission.rationaleDialog(activity, rationale).show();
            }
        }).start();
    }


    /**
     * 完成销毁activity
     */
    public static void finishActivity() {
        ActivityHelper.getInstance().finishActivity(RecordVideoActivity.class);
        ActivityHelper.getInstance().finishActivity(CameraActivity2.class);
        ActivityHelper.getInstance().finishActivity(ClipActivity.class);
    }

    /**
     * 打开相机以及相册权限检测
     *
     * @param activity
     */
    public static void showMediaSheet(@NonNull final Activity activity) {
        AndPermission.with(activity)
                .requestCode(REQUEST_CODE_PERMISSION_MULTI)
                .permission(new String[]{Manifest.permission.CAMERA})
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        switch (requestCode) {
                            case REQUEST_CODE_PERMISSION_MULTI: {
                                if (grantPermissions.contains(Manifest.permission.CAMERA)) {
                                    if (isFlyme() || Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                                        if (checkCamera()) {
                                            Dialoger.showAcionSheetDialog(activity);
                                        } else {
                                            DialogFragmentHelper.showTipsDialog(((AppCompatActivity) activity).getSupportFragmentManager(), activity.getString(R.string.str_permission_camera), new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    return;
                                                }
                                            });
                                        }
                                    } else {
                                        Dialoger.showAcionSheetDialog(activity);
                                    }
                                }
                                break;
                            }
                        }
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        switch (requestCode) {
                            case REQUEST_CODE_PERMISSION_MULTI: {
                                if (com.imay.live.utils.PermissionUtil.selfPermissionGranted(activity, Manifest.permission.CAMERA)) {
                                    Dialoger.showAcionSheetDialog(activity);
                                }
                                break;
                            }
                        }
                        if (AndPermission.hasAlwaysDeniedPermission(activity, deniedPermissions)) {
                            AndPermission.defaultSettingDialog(activity, REQUEST_CODE_PERMISSION_MULTI)
                                    .setTitle(R.string.permission_permission_title)
                                    .setMessage(R.string.permission_permission)
                                    .setPositiveButton(R.string.permission_button_setting)
                                    .show();
                        }
                    }
                }).rationale(new RationaleListener() {
            @Override
            public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                AndPermission.rationaleDialog(activity, rationale).show();
            }
        }).start();
    }

    /**
     * 判断是否有录音权限
     *
     * @return
     */
    private static boolean checkRecorderPermission() {
        try {
            // 音频获取源
            int audioSource = MediaRecorder.AudioSource.MIC;
            // 设置音频采样率，44100是目前的标准，但是某些设备仍然支持22050，16000，11025
            int sampleRateInHz = 44100;
            // 设置音频的录制的声道CHANNEL_IN_STEREO为双声道，CHANNEL_CONFIGURATION_MONO为单声道
            int channelConfig = AudioFormat.CHANNEL_IN_STEREO;
            // 音频数据格式:PCM 16位每个样本。保证设备支持。PCM 8位每个样本。不一定能得到设备支持
            int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
            // 缓冲区字节大小
            int bufferSizeInBytes = 0;
            bufferSizeInBytes = AudioRecord.getMinBufferSize(sampleRateInHz, channelConfig, audioFormat);
            //开始录制音频
            AudioRecord audioRecord = new AudioRecord(audioSource, sampleRateInHz,
                    channelConfig,
                    audioFormat,
                    bufferSizeInBytes);

            // 防止某些手机崩溃
            audioRecord.startRecording();

            /**
             * 根据开始录音判断是否有录音权限
             */
            if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
                return false;
            }

            //根据录音长度判断
            byte[] bytes = new byte[1024];
            int readSize = audioRecord.read(bytes, 0, 1024); //至于为什么写1024 我也不知道
            if (readSize == AudioRecord.ERROR_INVALID_OPERATION || readSize <= 0) {
                return false;
            }

            //如果短时间内频繁检测，会造成audioRecord还未销毁完成，此时检测会返回RECORDSTATE_STOPPED状态，再去read，会读到0的size，所以此时默认权限通过
            if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
                return true;
            }

            audioRecord.stop();
            audioRecord.release();//释放资源
            audioRecord = null;

            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } finally {

        }
        return false;
    }
}
